package com.hieu.tripmanager;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.hieu.abstracts.TripActivity;
import com.hieu.adapter.ActionAdapter;
import com.hieu.bean.Action;
import com.hieu.sql.DAL;
import com.hieu.util.Util;

public class ExpensesActivity extends TripActivity implements OnClickListener {
	// private Button btnSetTime;
	// private Button btnSetDate;
	private static final int REQUEST = 1000;
	private static final int REQUEST1 = 2000;
	private TextView txtDate;
	private TextView txtTime;
	private TextView txtDescription;
	private TextView txtAmount;
	private TextView txtSumEx;
	private TextView txtLastDate;
	private TextView txtNameTrip;
	private TextView txtCategory;
	private ImageView imgCate;
	private ImageView imgPosition;
	private String lastDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;
	private TimePickerDialog.OnTimeSetListener mTimeSetListener;
	private DatePickerDialog.OnDateSetListener mDateSetListener;
	private ListView listAction;
	private ArrayList<Action> mActionList, mActionList1;
	private ActionAdapter adapter;
	private DAL mDAL;
	private Button btnUpdate, btnAdd;
	private String nameTrip;
	private String cate = null;
	private String idAction;
	private String position = null;
	private Util util = new Util();
	// private ArrayList<Bitmap> arrayImg = new ArrayList<Bitmap>();
	private ArrayList<String> listPath = new ArrayList<String>();
	private String des = null;
	private String date = null;
	private String time = null;
	private String amount = null;
	private String amount1 = null;
	private String cate1 = null;

	private int check = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mDAL = new DAL(this);
		mActionList = new ArrayList<Action>();
		mActionList1 = new ArrayList<Action>();
		if (mDAL != null) {
			lastDate = mDAL.getLastDay(mDAL.getIdNotFinishTrip());
			nameTrip = mDAL.getNameNotFinishTrip();
		}
		if (nameTrip != null) {
			initRootView();
			initUIComponents();
			setListeners();
			// loadData();
		} else {
			setContentView(R.layout.layout);
			Toast.makeText(getBaseContext(),
					"Hiện tại không có chuyến đi mới!!!", Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	protected void initRootView() {
		setContentView(R.layout.expenses_activity_laytout);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void initUIComponents() {
		// Add header to Listview
		listAction = (ListView) findViewById(R.id.listAction);
//		View headerView = LayoutInflater.from(this).inflate(
//				R.layout.layout_expenses_header, null);
//		listAction.addHeaderView(headerView);

		btnAdd = (Button) findViewById(R.id.btnAdd);
		imgCate = (ImageView) findViewById(R.id.imgCate);
		imgPosition = (ImageView) findViewById(R.id.imgPosition);

		// Ẩn button Update
		btnUpdate = (Button) findViewById(R.id.btnUpdate);
		btnUpdate.setVisibility(View.INVISIBLE);

		// TextView Time and Date
		txtTime = (TextView) findViewById(R.id.txtTime);
		txtDate = (TextView) findViewById(R.id.txtDate);
		txtDescription = (TextView) findViewById(R.id.txtDescriptionEx);
		txtAmount = (TextView) findViewById(R.id.txtAmountEx);

		txtSumEx = (TextView) findViewById(R.id.txtSumMoneyDateEx);

		txtCategory = (TextView) findViewById(R.id.tv_category);

		// In ra tên chuyến đang thực hiện
		txtNameTrip = (TextView) findViewById(R.id.txtNameTripEx);
		txtNameTrip.setText(nameTrip);
		if ((date != null) || (time != null)) {
			txtDate.setText(date);
			txtTime.setText(time);
		} else {
			// Gọi hàm thời gian in ra Text view
			showTimePickerDialog();
			showDatePickerDialog();
		}
		txtDescription.setText(des);
		txtAmount.setText(amount);
		if (check == 0) {
			btnAdd.setVisibility(View.VISIBLE);
			btnUpdate.setVisibility(View.INVISIBLE);

		} else {
			btnAdd.setVisibility(View.INVISIBLE);
			btnUpdate.setVisibility(View.VISIBLE);

		}
		// In ra ngày cuối cùng
		txtLastDate = (TextView) findViewById(R.id.txtDateEx);
		// In ra các hoạt động ngày cuối
		if (lastDate != null) {
			// In ra ngày cuối cùng
			txtLastDate.setText(util.cutYear(lastDate));
			mActionList = mDAL.getActionList(lastDate);

			if (mActionList != null) {
				txtSumEx.setText(util.convertMoney(mDAL
						.getSumMoneyDate(lastDate)));
				adapter = new ActionAdapter(this, R.layout.list_action_item,
						mActionList);
				listAction.setAdapter(adapter);
			}
		} else {
			listAction.setEmptyView(null);
		}
	}

	@Override
	protected void setListeners() {
		txtCategory.setOnClickListener(this);
		txtTime.setOnClickListener(this);
		txtDate.setOnClickListener(this);
		btnAdd.setOnClickListener(this);
		btnUpdate.setOnClickListener(this);
		imgPosition.setOnClickListener(this);
		imgCate.setOnClickListener(this);
		listAction.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				check = 1;
				btnAdd.setVisibility(View.INVISIBLE);
				btnUpdate.setVisibility(View.VISIBLE);

				txtDescription.setText(mActionList.get(arg2 - 1)
						.getDescription());
				txtAmount.setText(util.convertMoney(mActionList.get(arg2 - 1)
						.getAmount()));
				txtDate.setText(mActionList.get(arg2 - 1).getDate());
				txtTime.setText(mActionList.get(arg2 - 1).getTime());

				amount1 = String.valueOf(mActionList.get(arg2 - 1).getAmount());
				cate1 = mActionList.get(arg2 - 1).getCate();

				date = String.valueOf(mActionList.get(arg2 - 1).getDate());
				time = String.valueOf(mActionList.get(arg2 - 1).getTime());
				idAction = mActionList.get(arg2 - 1).getIdAction();
				cate = cate1;
				listPath = new ArrayList<String>();
				listPath = mDAL.getImagePath(idAction);

			}
		});

		listAction.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				mDAL.deleteAction(mActionList.get(position - 1).getIdAction());
				lastDate = mDAL.getLastDay(mDAL.getIdNotFinishTrip());
				mActionList1 = mDAL.getActionList(lastDate);
				mActionList.clear();
				mActionList.addAll(mActionList1);
				adapter.notifyDataSetChanged();
				txtLastDate.setText(util.cutYear(lastDate));
				txtSumEx.setText(util.convertMoney(mDAL
						.getSumMoneyDate(lastDate)));
				txtDescription.setText("");
				txtAmount.setText("");
				Toast.makeText(view.getContext(), "Xóa thành công",
						Toast.LENGTH_SHORT).show();
				return false;
			}

		});
	}

	@Override
	protected void loadData() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imgPosition:
			if (check == 0) {
				des = txtDescription.getText().toString().trim();
				date = txtDate.getText().toString();
				time = txtTime.getText().toString();
				amount = txtAmount.getText().toString();
				Intent intent = new Intent(ExpensesActivity.this,
						LocationNearPlaceActivity.class);
				startActivityForResult(intent, REQUEST1);
			} else {
				Toast.makeText(this, "Không được phép cập nhật vị trí",
						Toast.LENGTH_SHORT).show();
			}
			break;

		case R.id.imgCate:
			des = txtDescription.getText().toString().trim();
			date = txtDate.getText().toString();
			time = txtTime.getText().toString();
			amount = txtAmount.getText().toString();
			Intent intent1 = new Intent(ExpensesActivity.this,
					ExpensesDocumentActivity.class);
			startActivityForResult(intent1, REQUEST);
			break;
		case R.id.txtTime:
			// Gọi dialog Set time
			TimePickerDialog timeDialog = new TimePickerDialog(this,
					mTimeSetListener, mHour, mMinute, true);
			timeDialog.show();
			break;
		case R.id.txtDate:
			// Gọi dialog Set date
			DatePickerDialog dateDialog = new DatePickerDialog(this,
					mDateSetListener, mYear, mMonth, mDay);
			dateDialog.show();
			break;
		case R.id.btnUpdate:
			if (mDAL != null) {
				des = txtDescription.getText().toString().trim();
				date = txtDate.getText().toString();
				time = txtTime.getText().toString();
				amount = txtAmount.getText().toString();
				Log.v("listPath", ""+listPath.size());
				if (!util.checkIsEmpty(des) && !util.checkIsEmpty(amount)) {
					if (!util.checkValiate(des)
							&& !util.checkValiateNumber(amount)) {
						if (cate != null) {
							if (util.checkAmount(Long.valueOf(amount),
									Long.valueOf(amount1), cate, cate1,
									ExpensesActivity.this)) {
								mDAL.updateAction(idAction, des, date, time,
										cate, Long.valueOf(amount), listPath);
								Toast.makeText(v.getContext(),
										"Cập nhật thông tin thành công",
										Toast.LENGTH_SHORT).show();
								lastDate = mDAL.getLastDay(mDAL
										.getIdNotFinishTrip());
								mActionList1 = mDAL.getActionList(lastDate);
								mActionList.clear();
								mActionList.addAll(mActionList1);
								adapter.notifyDataSetChanged();
								txtLastDate.setText(util.cutYear(lastDate));
								txtSumEx.setText(util.convertMoney(mDAL
										.getSumMoneyDate(lastDate)));
								btnAdd.setVisibility(View.VISIBLE);
								btnUpdate.setVisibility(View.INVISIBLE);

								check = 0;
								txtDescription.setText("");
								txtAmount.setText("");
								cate = null;
								listPath = new ArrayList<String>();
								showTimePickerDialog();
								showDatePickerDialog();
								;
							} else {
								Toast.makeText(
										v.getContext(),
										"Ngân sách cho mục hoạt động này không đủ",
										Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(v.getContext(),
									"Mời chọn danh mục cho hoạt động",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(v.getContext(),
								"Thông tin nhập vào chứa kí tự đặc biệt",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(v.getContext(), "Nhập thiếu thông tin",
							Toast.LENGTH_SHORT).show();
				}
			}

			break;
		case R.id.btnAdd:
			if (mDAL != null) {

				des = txtDescription.getText().toString().trim();
				amount = txtAmount.getText().toString().trim();
				date = txtDate.getText().toString();
				time = txtTime.getText().toString();

				if (!util.checkIsEmpty(des) && !util.checkIsEmpty(amount)) {
					if (!util.checkValiate(des)) {
						if (!util.checkDateTimeAction(date, time,
								ExpensesActivity.this)) {
							if (cate != null) {
								if (util.checkAmount(Long.valueOf(amount),
										cate, ExpensesActivity.this)) {

									mDAL.insertAction(des, date, time,
											Long.valueOf(amount), cate,
											listPath, position);
									Toast.makeText(v.getContext(),
											"Lưu thông tin thành công",
											Toast.LENGTH_SHORT).show();

									lastDate = mDAL.getLastDay(mDAL
											.getIdNotFinishTrip());
									mActionList1 = mDAL.getActionList(lastDate);
									mActionList.clear();
									mActionList.addAll(mActionList1);
									adapter.notifyDataSetChanged();
									txtLastDate.setText(util.cutYear(lastDate));
									txtSumEx.setText(util.convertMoney(mDAL
											.getSumMoneyDate(lastDate)));
									txtDescription.setText("");
									txtAmount.setText("");

									cate = null;
									listPath = new ArrayList<String>();
									position = null;
								} else {
									Toast.makeText(
											v.getContext(),
											"Ngân sách cho mục hoạt động này không đủ",
											Toast.LENGTH_SHORT).show();
								}
							} else {
								Toast.makeText(v.getContext(),
										"Mời chọn danh mục cho hoạt động",
										Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(v.getContext(),
									"Thời gian hoạt động bị trùng lặp",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(v.getContext(),
								"Thông tin nhập vào chứa kí tự đặc biệt",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(v.getContext(), "Nhập thiếu thông tin",
							Toast.LENGTH_SHORT).show();
				}
			}

			break;
		default:
			break;
		}
	}

	private void showDatePickerDialog() {
		// Lấy thời gian hiện tại
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		updateDisplay();
		mDateSetListener = new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				mYear = year;
				mMonth = monthOfYear;
				mDay = dayOfMonth;
				// Gọi hàm thời gian in ra Text view
				updateDisplay();
			}
		};
	}

	private void showTimePickerDialog() {
		// Lấy thời gian hiện tại
		final Calendar c = Calendar.getInstance();
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
		updateDisplay();
		mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				mHour = hourOfDay;
				mMinute = minute;
				// Gọi hàm thời gian in ra Text view
				updateDisplay();
			}
		};
	}

	// Show Date Time in TextView
	private void updateDisplay() {
		txtTime.setText(new StringBuilder().append(util.pad(mHour)).append(":")
				.append(util.pad(mMinute)));
		txtDate.setText(new StringBuilder().append(util.pad(mDay)).append("/")
				.append(util.pad(mMonth + 1)).append("/")
				.append(util.pad(mYear)));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if ((requestCode == REQUEST) && (resultCode == RESULT_OK)) {
			if (data != null) {
				cate = data.getStringExtra("cate");
				listPath = data.getStringArrayListExtra("image");
				for (int i = 0; i < listPath.size(); i++) {
					Log.v("path", "" + listPath.get(i));
				}
			}

		}
		if ((requestCode == REQUEST1) && (resultCode == RESULT_OK)) {
			if (data != null) {
				position = data.getStringExtra("position");
			}
		}

	}

}
